<?php
/**
 * This file is part of manage.
 * Author: tangzhou
 * Date: 2016/7/4
 * Time: 9:45
 * File: Vcc6016122201Controller.php
 */

namespace Ivr\HttpBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class Vcc6016122201Controller
 * @package Ivr\HttpBundle\Controller
 */
class Vcc6016122201Controller extends Controller
{
    const API_URL = 'https://backend.igengmei.com/api/phone/get_by_ext';
    const SECRET = 'YJK1LyG1tWAgIC%5';
    const KEY = 'xyaWTmdKNzU1GNUn';

    const TEST_API_URL = 'http://backend.test.gmei.com/api/phone/get_by_ext';
    const TEST_SECRET = 'LL#^wFk%mXV6!WUM';
    const TEST_KEY = 'pxahoVsHou1vekxE';

    /**
     * 更美IVR接口
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function getPhoneAction(Request $request)
    {
        $agPhone = $request->get('ag_phone', '');
        $callId = $request->get('call_id', '');
        if (empty($agPhone)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        //判断是不是BD
        $params = array();
        $params['ext'] = $agPhone;
        $params['key'] = self::KEY;
        $params['nonce'] = time().rand(1000, 9999);
        $params['created'] = time();
        $params['call_id'] = $callId;
        $params['sig'] = $this->getSign($params, self::SECRET);
        $this->get("logger")->info("发送params".json_encode($params));
        $response = $this->getResponse(self::API_URL, $params);
        $responseArray = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->get("logger")->error(sprintf('6016122201 VIP响应结果为非json格式，结果为【%s】.', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        $result = isset($responseArray['error_code']) ? $responseArray['error_code'] : 0;
        if ($result == 0 && isset($responseArray['data']['phone'][0])) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'phone' => $responseArray['data']['phone'][0],
                ),
            ));
        } else {
            $this->get("logger")->info(sprintf('6016122201获取失败%s', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
    }

    /**
     * 更美IVR接口(测试)
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function getPhoneTestAction(Request $request)
    {
        $agPhone = $request->get('ag_phone', '');
        $callId = $request->get('call_id', '');
        if (empty($agPhone)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        //判断是不是BD
        $params = array();
        $params['ext'] = $agPhone;
        $params['key'] = self::TEST_KEY;
        $params['nonce'] = time().rand(1000, 9999);
        $params['created'] = time();
        $params['call_id'] = $callId;
        $params['sig'] = $this->getSign($params, self::TEST_SECRET);
        $this->get("logger")->info("发送params".json_encode($params));
        $response = $this->getResponse(self::TEST_API_URL, $params);
        $responseArray = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->get("logger")->error(sprintf('6016122201 VIP响应结果为非json格式，结果为【%s】.', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        $result = isset($responseArray['error_code']) ? $responseArray['error_code'] : 0;
        if ($result == 0 && isset($responseArray['data']['phone'][0])) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'phone' => $responseArray['data']['phone'][0],
                ),
            ));
        } else {
            $this->get("logger")->info(sprintf('6016122201获取失败%s', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
    }

    /**
     * 获取sign
     *
     * @param array  $params 参数
     * @param string $secret 秘钥
     *
     * @return string
     */
    private function getSign($params, $secret)
    {
        $str = md5($secret.$params['nonce'].$params['created']);
        $newStr = substr($str, 0, 4).substr($str, 10, 6).substr($str, 30, 2);

        return $newStr;
    }

    /**
     * 发送请求
     *
     * @param string $url    接口地址
     * @param array  $params 参数
     *
     * @return mixed
     */
    private function getResponse($url, $params)
    {
        $url = $url.'?'.http_build_query($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $response = curl_exec($ch);
        $this->get("logger")->info(
            sprintf('6016122201 url【%s】params【%s】response【%s】.', $url, json_encode($params), $response)
        );

        return $response;
    }
}
